<?php
namespace App\Module\Admin\Service;

use App\Constants\Constant;
use App\Model\News;
use App\Model\Resource;
use App\Module\Admin\Request\News\CreateRequest;
use App\Module\Admin\Request\News\UpdateRequest;
use Hyperf\DbConnection\Db;

class NewsService {

    public function search($pagesize){
        return News::query()->latest("new_id")->paginate($pagesize);
    }

    public function create(CreateRequest $request){
        return Db::transaction(function () use($request){
            $news = new News();
            $news->fill($request->all());
            $news->save();

            if(!$request->has(["resources"])){
                return;
            }

            $resources = $request->input("resources");
            foreach ($resources as $v){
                $resource = new Resource();
                $resource->setAttribute("source_id",$news->new_id);
                $resource->setAttribute("uri",$v);
                $resource->setAttribute("origin",Constant::ORIGIN_NEWS);
                $resource->save();
            }
        });
    }

    public function getById($id){
        return News::query()->with("resources")->find($id);
    }

    public function update(UpdateRequest $request,$id){
        return Db::transaction(function ()use($request,$id){
            $news = News::query()->findOrFail($id);
            $news->fill($request->all());
            $news->save();

            Resource::query()->where([['source_id',$id],['origin',Constant::ORIGIN_NEWS]])->delete();

            if(!$request->has(["resources"])){
                return;
            }
            $resources = $request->input("resources");
            foreach ($resources as $v){
                $resource = new Resource();
                $resource->setAttribute("source_id",$id);
                $resource->setAttribute("uri",$v);
                $resource->setAttribute("origin",Constant::ORIGIN_NEWS);
                $resource->save();
            }
        });
    }

    public function delete($id){
        return Db::transaction(function () use($id){
            News::destroy($id);
            Resource::query()->where([['source_id',$id],['origin',Constant::ORIGIN_NEWS]])->delete();
        });
    }
}